package cn.wolfcode.web.modules.contract.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.PoiExportHelper;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;

import cn.wolfcode.web.modules.custinfo.entity.TbCustomer;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.service.SysUserService;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import cn.wolfcode.web.modules.contract.entity.TbContract;
import cn.wolfcode.web.modules.contract.service.ITbContractService;


import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @author 叶师傅
 * @since 2024-06-04
 */
@Controller
@RequestMapping("contract")
public class TbContractController extends BaseController {

    @Autowired
    private ITbContractService entityService;
    @Autowired
    private SysUserService sysUserService;

    private static final String LogModule = "TbContract";

    @GetMapping("/list.html")
    public String list() {
        return "tract/contract/list";
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('tract:contract:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        mv.setViewName("tract/contract/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('tract:contract:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("tract/contract/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('tract:contract:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String parameterValue) {
        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);
        IPage<TbContract> page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());
        // 查询条件 合同名称 合同编码  实体类TbContract， 是否盖章，审核状态 是否作废
        page = entityService.lambdaQuery()
                .like(!StringUtils.isEmpty(parameterName), TbContract::getContractName, parameterName)
                .eq(!StringUtils.isEmpty(parameterValue), TbContract::getAffixSealStatus, parameterValue)
                .or()
                .eq(!StringUtils.isEmpty(parameterValue), TbContract::getAuditStatus, parameterValue)
                .eq(!StringUtils.isEmpty(parameterValue), TbContract::getNullifyStatus, parameterValue)
                .like(!StringUtils.isEmpty(parameterName), TbContract::getContractCode, parameterName)//合同编码
                .page(page);


        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));
    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('tract:contract:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbContract entity) {
        entityService.save(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('tract:contract:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbContract entity) {
        entityService.updateById(entity);
        return ResponseEntity.ok(ApiModel.ok());
    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('tract:contract:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {
        entityService.removeById(id);
        return ResponseEntity.ok(ApiModel.ok());
    }
    @RequestMapping("/export")
    public void export(HttpServletResponse response,
                       String custId,
                       String contractName,
                       String contractCode)
            throws UnsupportedEncodingException {
        //1. 准备你需要导出的数据
        List<TbContract> tbCustomerList = entityService.lambdaQuery()
                .like(!org.springframework.util.StringUtils.isEmpty(custId),TbContract::getCustId,custId)
                .or()
                .like(!org.springframework.util.StringUtils.isEmpty(contractName),TbContract::getContractName,contractName)
                .eq(!org.springframework.util.StringUtils.isEmpty(contractCode),TbContract::getContractCode,contractCode)
                .list();


        //设置属性
        ExportParams exportParams=new ExportParams();
        //2. 封装成workbook
        /**
         * 参数一: 表格属性
         * 参数二: 你需要导出的实体类的字节码  需要配合@Excel注释使用
         * 参数三: 你需要导出的数据
         */
        Workbook workbook = ExcelExportUtil.exportExcel
                (exportParams,
                        TbContract.class,
                        tbCustomerList);
        //3. 导出
        /**
         * 参数一 需要一个响应
         * 参数二 文件名字
         * 参数三 工作簿
         */
        PoiExportHelper.exportExcel(response,"合同管理",workbook);
    }

}
